package com.yupi.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.yupi.usercenter.common.ErrorCode;
import com.yupi.usercenter.common.UserQuery;
import com.yupi.usercenter.exception.BusinessException;
import com.yupi.usercenter.model.domain.Team;
import com.yupi.usercenter.model.domain.User;
import com.yupi.usercenter.model.domain.request.UserRegisterRequest;
import com.yupi.usercenter.service.UserService;
import com.yupi.usercenter.mapper.UserMapper;
import com.yupi.usercenter.utils.AlgorithmUtils;
import javafx.util.Pair;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.Array;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.yupi.usercenter.contant.UserConstant.ADMIN_ROLE;
import static com.yupi.usercenter.contant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户服务实现类
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;


    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "yupi";

    /**
     * 用户注册
     *
     * @param userAccount   用户账户
     * @param userPassword  用户密码
     * @param checkPassword 校验密码
     * @param planetCode    星球编号
     * @return 新用户 id
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword, String planetCode) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, planetCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (planetCode.length() > 5) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号过长");
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return -1;
        }
        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            return -1;
        }
        // 账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }
        // 星球编号不能重复
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("planetCode", planetCode);
        count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编号重复");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 3. 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setPlanetCode(planetCode);
        boolean saveResult = this.save(user);
        if (!saveResult) {
            return -1;
        }
        return user.getId();
    }





    /**
     * 用户注册 更新版·
     *
     * @return 新用户 id
     */
    @Override
    public long userRegister(UserRegisterRequest userRegisterRequest,String filePath) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userRegisterRequest.getUserAccount(), userRegisterRequest.getUserPassword(),userRegisterRequest.getCheckPassword(), userRegisterRequest.getPlanetCode(),userRegisterRequest.getUsername(),userRegisterRequest.getEmail(),userRegisterRequest.getPhone())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }

        if (userRegisterRequest.getUserAccount().length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userRegisterRequest.getUserPassword().length() < 8 || userRegisterRequest.getCheckPassword().length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (userRegisterRequest.getPlanetCode().length() > 5) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号过长");
        }

        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userRegisterRequest.getUserAccount());
        if (matcher.find()) {
            return -1;
        }
        // 密码和校验密码相同
        if (!userRegisterRequest.getUserPassword().equals(userRegisterRequest.getCheckPassword())) {
            return -1;
        }
        // 账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userRegisterRequest.getUserAccount());
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }
        // 星球编号不能重复
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("planetCode", userRegisterRequest.getPlanetCode());
        count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编号重复");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userRegisterRequest.getCheckPassword()).getBytes());

        // 5. 邮箱校验（格式+唯一性）
        String emailPattern = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
        if (!Pattern.matches(emailPattern, userRegisterRequest.getEmail())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱格式错误");
        }
        if (userMapper.selectCount(new QueryWrapper<User>().eq("email", userRegisterRequest.getEmail())) > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱已被注册");
        }

        // 6. 手机号校验（格式+唯一性）
        String phonePattern = "^1[3-9]\\d{9}$";
        if (!Pattern.matches(phonePattern, userRegisterRequest.getPhone())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "手机号格式错误");
        }
        if (userMapper.selectCount(new QueryWrapper<User>().eq("phone", userRegisterRequest.getPhone())) > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "手机号已被注册");
        }

       /* createTime
                isDelete
        tags
                updateTime
        userRole
                userStatus
        */
        // 3. 插入数据
        User user = new User();
        BeanUtils.copyProperties(userRegisterRequest, user);
        user.setCreateTime(new Date());
        user.setIsDelete(0);
        user.setUpdateTime(new Date());
        user.setUserRole(0);
        user.setUserStatus(0);
        //这个的动态的 不是写死的ok
        user.setAvatarUrl(filePath);
        //todo  这个功能需要开发的 后面开
        user.setTags("['java','python']");

        int saveResult = userMapper.insert(user);
        return saveResult;
    }








    /**
     * 用户登录 ✔️
     *
     * @param userAccount  用户账户
     * @param userPassword 用户密码
     * @param request
     * @return 脱敏后的用户信息
     */
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return null;
        }
        if (userAccount.length() < 4) {
            return null;
        }
        if (userPassword.length() < 8) {
            return null;
        }

        // 账户不能包含特殊字符  这个是难点
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return null;
        }

        // 2. 加密 md5加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            return null;
        }
        // 3. 用户脱敏
        User safetyUser = getSafetyUser(user);
        // 4. 记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);
        return safetyUser;
    }

    /**
     * 用户脱敏  ✔️
     * 脱敏 了 password 等敏感信息
     * @param originUser
     * @return
     */
    @Override
    public User getSafetyUser(User originUser) {
        if (originUser == null) {
            return null;
        }

        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setUsername(originUser.getUsername());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setAvatarUrl(originUser.getAvatarUrl());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setPhone(originUser.getPhone());
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setPlanetCode(originUser.getPlanetCode());
        safetyUser.setUserRole(originUser.getUserRole());
        safetyUser.setUserStatus(originUser.getUserStatus());
        safetyUser.setCreateTime(originUser.getCreateTime());
        safetyUser.setTags(originUser.getTags());
        return safetyUser;
    }

    /**
     * 用户注销
     *
     * @param request
     */
    @Override

    public int userLogout(HttpServletRequest request) {
        // 移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }



    /**
     *   根据标签搜索用户。 ✔️ lambdar表达式 重点账掌握  现阶段一看就懂 自己打就废
     * @param tagNameList  用户要搜索的标 签  duihao
     * @return
     */
    /**
     * 根据标签搜索用户。
     *
     * @param tagNameList
     * @return
     */
    @Override
    public List<User> searchUsersByTags(List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        List<User> userList = userMapper.selectList(new QueryWrapper<>());
        Gson gson = new Gson();
        return userList.stream()
                .filter(user -> {
                   // ["男","Java", "Python", "AI"] tagStr 的数据结构
                    String tagStr = user.getTags();
                    if (StringUtils.isBlank(tagStr)) return false;

                    try {
                        // element 的数据结构 是JsonArray  字符串  0 : "男"    1 : "Python"  2 :  "AI"  3 : "java"
                        JsonElement element = gson.fromJson(tagStr, JsonElement.class);
                        Set<String> tagSet = new HashSet<>();

                        if (element.isJsonArray()) {
                            // 解析数组
                            tagSet = gson.fromJson(element, new TypeToken<Set<String>>(){}.getType());
                        } else if (element.isJsonPrimitive()) {
                            // 处理单字符串标签（兼容旧数据）
                            String tags = element.getAsString().trim();
                            if (tags.startsWith("[") && tags.endsWith("]")) {
                                tags = tags.substring(1, tags.length() - 1);
                            }
                            // tagSet 数据结构 是 LinkedHashSet  0 : "男"    1 : "Python"  2 :  "AI"  3 : "java"
                            tagSet.addAll(Arrays.asList(tags.split(",")));
                        } else {
                            log.warn("非法标签格式 - 用户ID: {} 内容: {}", user.getId(), tagStr);
                            return false;
                        }

                        // 空集合直接过滤
                        if (tagSet.isEmpty()) return false;

                        // 统一小写处理（可选）
                        Set<String> lowerTagSet = tagSet.stream()
                                .map(String::toLowerCase)
                                .collect(Collectors.toSet());
                        List<String> lowerTargetTags = tagNameList.stream()
                                .map(String::toLowerCase)
                                .collect(Collectors.toList());

                        return lowerTagSet.containsAll(lowerTargetTags);
                    } catch (JsonSyntaxException e) {
                        log.error("标签解析异常 - 用户ID: {} 内容: {}", user.getId(), tagStr, e);
                        return false;
                    }
                })
                .map(this::getSafetyUser)
                .collect(Collectors.toList());
    }

    @Override
    public Page<User> searchUsersByTags(UserQuery userQuery) {
        // 参数校验
        if (CollectionUtils.isEmpty(userQuery.getTagNameList())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (userQuery.getPageNum() < 1 || userQuery.getPageSize() < 1) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "分页参数错误");
        }

        // 1. 获取全量数据（后续可优化为SQL过滤）
        List<User> allUsers = userMapper.selectList(new QueryWrapper<>());

        // 2. 内存中过滤标签
        Gson gson = new Gson();
        List<User> filteredUsers = allUsers.stream()
                .filter(user -> checkUserTags(user, gson, userQuery.getTagNameList()))
                .map(this::getSafetyUser)
                .collect(Collectors.toList());

        // 3. 手动分页逻辑
        return manualPagination(filteredUsers, userQuery.getPageNum(), userQuery.getPageSize());
    }

    // 标签检查逻辑封装
    private boolean checkUserTags(User user, Gson gson, List<String> targetTags) {
        String tagStr = user.getTags();
        if (StringUtils.isBlank(tagStr)) return false;

        try {
            JsonElement element = gson.fromJson(tagStr, JsonElement.class);
            Set<String> tagSet = new HashSet<>();

            // 解析标签逻辑（保持原有实现）
            if (element.isJsonArray()) {
                tagSet = gson.fromJson(element, new TypeToken<Set<String>>(){}.getType());
            } else if (element.isJsonPrimitive()) {
                String tags = element.getAsString().trim();
                if (tags.startsWith("[") && tags.endsWith("]")) {
                    tags = tags.substring(1, tags.length() - 1);
                }
                tagSet.addAll(Arrays.asList(tags.split(",")));
            } else {
                log.warn("非法标签格式 - 用户ID: {} 内容: {}", user.getId(), tagStr);
                return false;
            }

            // 空集合过滤
            if (tagSet.isEmpty()) return false;

            // 统一小写处理
            Set<String> lowerTagSet = tagSet.stream()
                    .map(String::toLowerCase)
                    .collect(Collectors.toSet());
            List<String> lowerTargetTags = targetTags.stream()
                    .map(String::toLowerCase)
                    .collect(Collectors.toList());

            return lowerTagSet.containsAll(lowerTargetTags);
        } catch (JsonSyntaxException e) {
            log.error("标签解析异常 - 用户ID: {} 内容: {}", user.getId(), tagStr, e);
            return false;
        }
    }

    // 手动分页实现
    private Page<User> manualPagination(List<User> data, int pageNum, int pageSize) {
        Page<User> page = new Page<>(pageNum, pageSize);

        // 计算分页参数
        int total = data.size();
        page.setTotal(total);
        page.setPages((total + pageSize - 1) / pageSize); // 总页数

        // 分页数据截取
        int fromIndex = (pageNum - 1) * pageSize;
        if (fromIndex >= total) {
            page.setRecords(Collections.emptyList());
            return page;
        }

        int toIndex = Math.min(fromIndex + pageSize, total);
        page.setRecords(data.subList(fromIndex, toIndex));

        return page;
    }


    @Override
    public User getLoginUser(HttpServletRequest request) {
        if (request == null) return null;
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        return (User) userObj;
    }

    @Override
    public int updateUser(User user, User loginUser) {
        Long userId = user.getId();
        if (userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //管理员 可以修改任意用户
        //用户只能修改自己的账号
        // TODO: 2025/1/5   这个逻辑右误差
        if ((!userId.equals(loginUser.getId())) && (!isAdmin(loginUser))) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        User oldUser = userMapper.selectById(userId);
        if (oldUser == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return userMapper.updateById(user);
    }

    @Override
    public boolean isAdmin(User loginUser) {
        return loginUser != null && loginUser.getUserRole() == ADMIN_ROLE;
    }

    @Override
    public boolean isAdmin(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        return user != null && user.getUserRole() == ADMIN_ROLE;
    }




    /**
     * 推荐匹配用户
     * @param num
     * @param loginUser
     * @return
     */
    @Override
    public List<User> matchUsers(long num, User loginUser) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("tags");
        queryWrapper.ne("tags", "");
        queryWrapper.select("id", "tags");
        List<User> userList = this.list(queryWrapper);

        Gson gson = new Gson();
        List<String> loginTags = safeParseTags(gson, loginUser.getTags());

        List<Pair<User, Long>> list = new ArrayList<>();
        for (User user : userList) {
            if (user.getId() == loginUser.getId()) {
                continue;
            }
            List<String> userTags = safeParseTags(gson, user.getTags());
            if (userTags.isEmpty()) {
                continue;
            }
            long distance = AlgorithmUtils.minDistance(loginTags, userTags);
            list.add(new Pair<>(user, distance));
        }

        List<Pair<User, Long>> sortedList = list.stream()
                .sorted(Comparator.comparingLong(Pair::getValue))
                .limit(num)
                .collect(Collectors.toList());

        List<Long> userIds = sortedList.stream()
                .map(pair -> pair.getKey().getId())
                .collect(Collectors.toList());

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.in("id", userIds);
        Map<Long, User> userMap = this.list(userQueryWrapper).stream()
                .map(this::getSafetyUser)
                .collect(Collectors.toMap(User::getId, u -> u));

        return userIds.stream()
                .map(userMap::get)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }


    /**
     * 修改用户的标签
     *
     */
    @Override
    public int updateTags(String oldTag, String newTag, String operation, User loginUser) {
        long userId = loginUser.getId();
        if (userId < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户ID无效");
        }

        User oldUser = userMapper.selectById(userId);
        if (oldUser == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "用户不存在");
        }

        // 1. 获取当前用户的标签并转换成列表
/*
        List<String> currentTags = convertJsonToTags(oldUser.getTags());
*/
        List<String> currentTags = parseTagsWithGson(oldUser.getTags());


        // 2. 根据操作类型处理标签
        switch (operation.toLowerCase()) {
            case "add":
                if (!currentTags.contains(newTag)) {
                    currentTags.add(newTag);  // 添加新标签
                } else {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "标签已存在");
                }
                break;

            case "remove":
                if (currentTags.contains(oldTag)) {
                    currentTags.remove(oldTag);  // 删除旧标签
                    // 如果标签列表中删除后出现空字符串，移除空字符串
                    currentTags.removeIf(tag -> tag.isEmpty());
                } else {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "未找到指定的标签");
                }
                break;

            case "update":
                if (currentTags.contains(oldTag)) {
                    int index = currentTags.indexOf(oldTag);  // 获取旧标签的索引
                    currentTags.set(index, newTag);  // 替换为新标签
                } else {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "未找到指定的标签");
                }
                break;

            default:
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "无效的操作类型");
        }

        // 3. 更新数据库中的标签字段
        String updatedTagsJson = convertTagsToJson(currentTags);
        oldUser.setTags(updatedTagsJson);

        return userMapper.updateById(oldUser);  // 更新数据库中的用户信息
    }

    // 转换标签字符串为列表
    private List<String> convertJsonToTags(String tagsJson) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(tagsJson, new TypeReference<List<String>>() {
            });
        } catch (JsonProcessingException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标签格式错误");
        }
    }

    // 转换标签列表为JSON字符串
    private String convertTagsToJson(List<String> tags) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.writeValueAsString(tags);
        } catch (JsonProcessingException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标签格式错误");
        }
    }

    public List<String> parseTagsWithGson(String tagsJson) {
        Gson gson = new Gson();

        // 处理转义字符
        String cleanedJson = tagsJson
                .replaceAll("^\"|\"$", "")
                .replace("\\\"", "\"");

        return gson.fromJson(cleanedJson,
                new TypeToken<List<String>>(){}.getType());
    }







    private List<String> safeParseTags(Gson gson, String tagsJson) {
        if (StringUtils.isBlank(tagsJson)) {
            return Collections.emptyList();
        }
        try {
            return gson.fromJson(tagsJson, new TypeToken<List<String>>() {}.getType());
        } catch (JsonSyntaxException e) {
            return Collections.emptyList();
        }
    }

}


